package com.qf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.entity.Stock;
import com.qf.entity.StockParam;
import com.qf.mapper.StockMapper;
import com.qf.service.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: 你的名字
 * @Date: 2021/07/10/14:32
 * @Description:
 */
@Service("stockService")
public class StockServiceimpl extends ServiceImpl<StockMapper,Stock> implements StockService {
  @Autowired
   private TransactionTemplate template;
    @Override
    public boolean lockStock(List<StockParam> stockParamList) {

       return template.execute(new TransactionCallback<Boolean>() {
           @Override
           public Boolean doInTransaction(TransactionStatus status) {
               //设置事务保存点
               Object savepoint = status.createSavepoint();
               boolean falg=true;
               for (StockParam stockParam : stockParamList) {
                Integer stock=   baseMapper.lockStock(stockParam);
                if (stock<=0){
                    falg=false;
                    status.rollbackToSavepoint(savepoint);
                    break;
                }
               }

               return falg;
           }
       });

    }

    @Override
    public boolean unlock(List<StockParam> list) {
        return template.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus status) {
                Object savepoint = status.createSavepoint();
                for (StockParam stockParam : list) {
                    Integer stock = baseMapper.unLockGoodsStock(stockParam);
                    if (stock <= 0) {
                        status.rollbackToSavepoint(savepoint);
                        return false;
                    }
                }
                return true;
            }
        });
    }

}

